package com.youthburin.utils;

import java.io.OutputStream;
import java.io.StringWriter;

import org.codehaus.jackson.JsonEncoding;
import org.codehaus.jackson.JsonGenerator;
import org.codehaus.jackson.map.ObjectMapper;

public class JsonUtils {
	private static final ObjectMapper objectMapper = new ObjectMapper();

	public static void writeObject(OutputStream out, Object obj) {
		writeObject(out, obj, JsonEncoding.UTF8);
	}

	public static void writeObject(OutputStream out, Object obj, JsonEncoding encoding) {
		try {
			JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(out, encoding);
			objectMapper.writeValue(jsonGenerator, obj);
		} catch (Exception ex) {
			throw new RuntimeException("Could not write JSON: " + ex.getMessage(), ex);
		}

	}

	public static String getJson(Object obj) {
		try {
			StringWriter sw = new StringWriter();
			JsonGenerator jsonGenerator = objectMapper.getJsonFactory().createJsonGenerator(sw);
			objectMapper.writeValue(jsonGenerator, obj);

			return sw.toString();
		} catch (Exception ex) {
			throw new RuntimeException("Could not write JSON: " + ex.getMessage(), ex);
		}

	}
}
